package com.sina.shop.manage.aop;

import com.sina.shop.domain.admin.Admin;
import com.sina.shop.domain.log.Log;
import com.sina.shop.manage.service.admin.AdminManageService;
import com.sina.shop.manage.service.log.LogManageService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * Description:  对后台每次增删改操作增加日志管理
 * 段浩杰   2018-01-12-11:19
 */
@Aspect
@Component("addLog")
public class AddLog {

    protected final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("logManageService")
    private LogManageService logManageService;

    @Autowired
    @Qualifier("adminManageService")
    private AdminManageService adminManageService;

    @Pointcut("execution(public * com.sina.shop.manage.service..save*(..))")//给切入点起一个别名（必须是方法）
    public void methodSave() {
    }

    @Pointcut("execution(public * com.sina.shop.manage.service..update*(..))")//给切入点起一个别名（必须是方法）
    public void methodUpdate() {
    }

    @Pointcut("execution(public * com.sina.shop.manage.service..delete*(..))")//给切入点起一个别名（必须是方法）
    public void methodDelete() {
    }

    @After("methodSave()||methodUpdate()||methodDelete()")
    public void execute(JoinPoint point) {
        //设置操作
        String methodName = point.getSignature().getName();
        Log log = new Log();

        //设置操作者
        String account = (String) SecurityUtils.getSubject().getPrincipal();
        Admin admin = adminManageService.getAdmin(account);
        log.setAdmin(admin);

        if (!methodName.equals("saveLog")) {
            //保存日志
            String classNames[] = point.getTarget().getClass().getName().toString().split("\\.");
            String className = classNames[classNames.length - 1];
            String make = "执行 " + className + " 下的 " + methodName + "方法";
            log.setMake(make);
            logManageService.saveLog(log);

        }
    }
}
